const express = require('express');
const router = express.Router();

let fs = require('fs');
const path = require('path');
const infoMacs = require("../../src/components/infoMacs");
const passport = require('passport');

const jwt = require('jsonwebtoken');
const secret = process.env.JWT_SECRET_KEY || 'change-me';

router.get('/csrf', (req, res) => {
    return res.json({csrfToken: res.locals._csrf});
});

router.get('/session', (req, res) => {
    let session = {
        clientMaxAge: 60000, // 60 seconds
        csrfToken: res.locals._csrf
    };
    if (req.user) {
        session.user = req.user;
        const body = {'_id': req.user._id, 'username': req.user.username, 'roles': req.user.roles};
        const token = jwt.sign({user: body}, secret);
        session.authToken = token
    }

    return res.json(session)
});

router.post('/login',
    passport.authenticate('local', {successRedirect: '/'}));

router.post('/logout', (req, res) => {
    req.logout();
    res.redirect('/');
});


router.get('/setMacBylicense', (req, res) => {
    let getString = req.query.license;

    infoMacs.macCrty = getString;
    let getPath = path.join(__dirname, '../../src/components/', 'infoMacs.json');
    fs.writeFile(getPath, JSON.stringify(infoMacs), function (err) {

        if (err) return console.log(err);
        let getString = new Buffer.from(infoMacs.macCrty, 'base64').toString();
        let getStringNumber = parseInt(getString);
        console.log(decodeURI("%E5%B7%B2%E6%BF%80%E6%B4%BB%E5%88%B0")+'：' + new Date(getStringNumber).toLocaleString());

    });

    req.logout();
    res.redirect('/');

});

module.exports = router;